package com.simon.study.algorithm.review;

import cn.hutool.core.collection.CollUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * <p>
 *
 * @author simon
 */
public class CountdownLatchTest {
    public static final ThreadPoolExecutor pool = new ThreadPoolExecutor(2, Runtime.getRuntime().availableProcessors(), 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024));

    public static void main(String[] args) {
        List<Integer> resultList = new ArrayList<>(100);
        IntStream.range(0,100).forEach(resultList::add);

        List<List<Integer>> split = CollUtil.split(resultList, 10);

        CountDownLatch downLatch = new CountDownLatch(100);
        for (List<Integer> list : split) {
            pool.execute(() -> list.forEach( i-> {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    downLatch.countDown();
                    System.out.println("Acquire execution privilege with count " + downLatch.getCount());
                }
            }));
        }

        try {
            downLatch.await();
            System.out.println("End execution...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
